我正在学习c ++,我的老师写了这段代码:
Tpoint并且TObjetGraphique是两个分开的类
origine是类型的对象Tpoint声明private内TObjetGraphiqueRun Code Online (Sandbox Code Playgroud)TPoint TObjetGraphique::getOrigine() const {return (TPoint(origine));}
我想知道为什么我们不会写:
TPoint TObjetGraphique::getOrigine() const
{return origine;}
Run Code Online (Sandbox Code Playgroud)
有什么区别吗?
教师代码中的演员阵容毫无意义
Run Code Online (Sandbox Code Playgroud)TPoint TObjetGraphique::getOrigine() const {return (TPoint(origine));} // ^^^^^^^ ^ You can just omit this as proposed
假设origine是所述的类型TPoint.
如果origine可以以TPoint任何方式转换类型,则显式转换也是无意义的.
如果有这种语法的原因那么它TPoint有构造函数声明,如
struct SomethingElse {
int a_;
int b_;
explicit SomethingElse(int a, int b) : a_(a), b_(b) {}
SomethingElse() = default;
};
class TPoint {
public:
explicit TPoint(SomethingElse rhs) : x_(rhs.a_), y_(rhs.b_) {
std::cout << "TPoint::TPoint(const SomethingElse& rhs)" << std::endl;
}
private:
int x_;
int y_;
};
int main() {
SomethingElse something;
// TPoint pt1({2,3}); // <<<<<<<<<< Fails
TPoint pt2(something);
}
Run Code Online (Sandbox Code Playgroud)
这看起来很不寻常,但最终会阻止TPoint被SomethingElse无意中实例化(参见Live Demo).