我一直被教導說類的實例語法
1. Class c(arg);
和
2. Class c = arg;
是兩個完全等效的語句,但看這情形。
#include <iostream>
class Intermediary {
};
class Left {
public:
Left(const Intermediary &) {
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
};
class Right {
public:
// The argument is there just so that the example can work, see below
Right(int) {
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
operator Intermediary() const {
std::cout << __PRETTY_FUNCTION__ << std::endl;
return Intermediary();
}
};
現在,如果我這樣做:
Left l = Right(0);
編譯器會抱怨
error: conversion from Right to non-scalar type Left requested
但是,如果我這樣做:
Left l(Right(0));
然後,一切都編譯並輸出是
Right::Right(int)
Right::operator Intermediary() const
Left::Left(const Intermediary&)
但是,如果我這樣做:
Left l = (Intermediary)Right(0);
然後一切重新編譯和輸出就像上面的一個。
所以很明顯
1. Class c(arg);
和
2. Class c = arg;
是不一樣的,但爲什麼不呢,這有什麼區別?我在網上找不到任何東西。
答案是您被教導錯誤。 –