我试图用C++编写一个构造函数(我是新的).
我的尝试:
class Tree
{
private:
int leaf;
public:
Tree(int leaf); //constructor
};
Tree::Tree(int leaf) //constructor
{
strcpy(this->leaf, leaf);
}
Run Code Online (Sandbox Code Playgroud)
这是怎么做的正确方法?因为我发现许多不同版本的srcpy,没有等等.
不它不是.strcpy用于复制以null结尾的字符串.使用构造函数初始化列表:
Tree::Tree(int leaf) : leaf(leaf) {}
Run Code Online (Sandbox Code Playgroud)
还要注意的是你的构造允许从隐式转换int到Tree.所以你可以做这样的事情:
Tree t = 4 + 5;
Run Code Online (Sandbox Code Playgroud)
如果您不想要此行为,请将构造函数显式标记:
explicit Tree(int leaf);
Run Code Online (Sandbox Code Playgroud)