类的构造函数是返回类类型的引用,还是只返回一段内存
Does the constructor of a class return a reference of the class type or just a piece of memory?
据我所知,构造函数没有返回类型。但在下面的代码中,看起来ctor确实返回了一个const引用对象(ctor的返回类型是隐藏的const引用aclass吗?),(或者)返回了一段const引用(Q1)类型的内存?还是这是别的东西(Q1)?这些对象是由ctor(Q2)返回的有效对象吗?它们等价于c stack_object;
(Q2?请分享你的想法。
#include<iostream>
using namespace std;
class c{
public:
int x = 88;
c(int i){
x=i;
// cout<<"nc1 ctorn";
}
c(){
// cout<<"nc ctorn";
}
~c(){
// cout<<"nc dtorn";
}
};
int f(){
const c & co1 = c(); //ctor returns a const reference obj of type c class
c &ref = const_cast<c&>(co1); //casting away const
cout<<"n addr3 = "<<&ref<<"n"; //another new address
ref.x = 99;
//cout<<ref.x;
}
int main(){
const c &co = c(3);
c *p = const_cast<c*>(&co);
cout<<"n addr1 = "<<p<<"n";
//cout<<p->x; //out puts 3
p->x = 11; //just assigning some new values
const c & co1 = c();
c *p1 = const_cast<c*>(&co1);
cout<<"n addr2 = "<<p1<<"n"; //new address
//cout<<"n"<<p1->x;
f();
cout<<"n main() Donen";
return 0;
}
o/p此处:
addr1 = 0xbfc3c248
addr2 = 0xbfc3c24c
addr3 = 0xbfc3c214
main() Done
正如您所指出的,构造函数不返回任何内容;它没有返回类型。
在代码中执行以下操作的部分:
const c &co = c(3);
可以这样说:
表达式
c(3)
是类型为c
的右值。
但是,您正在创建一个临时对象,并将引用绑定到它。通常,临时对象的生存期在该语句/序列点的末尾结束。然而,C++标准保证了其使用寿命的延长。
相关文章:
- 在做一段时间内检查字符的无限循环
- 如何为一段代码启用 -permissive
- ExtTextOut 文本的持续闪烁,在一段时间后,文本将恢复为默认字体
- 对于等待以 std::future wait() 返回的函数的 CPU 使用率或检查标志在循环中休眠一段时间哪个更好?
- 使用Qt Creator在调试模式下编译一段代码
- ::grpc::ServerReaderWriter 对象在另一个线程中一段时间后无法调用
- 一段时间后 CPU 使用率高
- 有没有办法在一段时间后将流程从流出中分离出来
- 无法理解一段具有完美转发和省略号的C++代码
- 如何返回一串字母数字字符中的最大值(例如-1A003B3)?
- 在一段时间内更改标签文本
- 解决PNP在一段时间后返回坏的rvec和tvec
- 如何从一段时间返回继续
- 我的函数返回的是打印到控制台,它只会在我调用它时每隔一段时间C++
- libcurl:curl_easy_performer在一段时间后失败,返回CURLE_SSL_CACERT_BADFI
- LoadBitmap在程序运行一段时间后返回NULL
- C++基于 TCP 的服务器套接字需要一段时间才能返回 10054 错误。它不会立即返回
- 在Poco c++库中发送调用在运行一段时间后在Windows上不返回
- 由于ECHILD错误,C++中的system()函数在一段时间内运行良好,但在返回-1时失败.为什么?
- 类的构造函数是返回类类型的引用,还是只返回一段内存