从方法中按值返回类类型的变量
Returning an variable of class' type by value from the method
先生们,美好的一天!让我们考虑一下代码:
class Test
{
int a;
public:
Test(){}
Test( Test& t){cout<<"hellon";} //copy constructor
Test foo() { return Test();}
};
int main()
{
Test t;
}
问题是给定的代码没有编译。如果我们删除复制构造函数,一切顺利。问题出在哪里?添加常量 - Test(const Test& t)
解决了问题,但我不明白为什么。谁能解释一下?谢谢!
Test( Test& t){cout<<"hellon";}
是的,这是一个复制构造函数。
但是,我们通常这样写:
Test(const Test& t){cout<<"hellon";}
那是因为它以这种方式更有用;这是我们从"临时"(例如你的表达式Test()
)复制构造Test
的唯一方法,因为只有引用到const
(和右值引用)可以绑定到临时引用。
这与以下问题相同:
int& r1 = 3; // :(
const int& r2 = 3; // :D
或:
int& r1 = f(); // :(
const int& r2 = f(); // :D
相关文章:
- 从模板创建通用打印函数,以打印基元数据类型变量的值
- 指针数据类型变量如何包含对象?
- 将 static_cast<int>(-15) 分配给静态常量字符类型变量
- 将内置类型变量传递给只有一个类类型参数的"+"运算符函数时自动类型转换的构造函数
- 如何为结构类型变量赋值
- 如何将字符类型变量附加到字符串中?
- 共享或私有 openmp 代码中的结构化类型变量
- 有没有办法在 c++ 中制作类型变量?
- 从其他类声明类类型变量会给出 C2143 错误(在"*"之前缺少";")
- 如何检查类中定义的枚举类型变量是否被分配给?
- 将子类实例保存在父类型变量中并通过父变量使用 Child 函数?
- 是否可以在没有结构的情况下创建新的类型变量?
- 为什么类型变量;不调用默认 CTR
- 如何使用CIN将输入整数值获取到char类型变量中
- 如何为 char** 类型变量提供适当的值,以便将其分配给字符串变量
- 在C++标准中哪里说必须初始化 const 内置类型变量的定义
- 为什么可以将其他类型变量用作C 中常量参考参数参数的参数
- Eclipse CDT 打开声明的自动类型变量
- 如何计算长长类型变量中的位数
- 将自动类型变量初始化为零.这种类型安全吗?