引用的例子,

vloso 2018-05-30 11:34:57
class Array
{
Array& operator=(.....);

};

Array& Array::operator=(.....)
{
}



昨天我的提问是 (Array&+(Array::operator=(.....))后面的函数 是怎么样的一个原理,初步理解是这么的一回事,Array&为声明是一个函数的返回值(返回值理解为 结果)是一个引用的类型。。

在这里我不是很明白,恳请老师按照上述的 帮忙完全一个示例,然后可在 int main调试 里面运行,我想解刨一下原理的


因为书本的代码太多了,不太明白,所以求助各位老师的不胜感激
...全文
1128 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
ooolinux 2018-06-01
  • 打赏
  • 举报
回复
Student& Student::operator=(const Student& rhs) 返回类型改成Student(去掉引用)也是可以的,不过 c=b=a; 会多两次拷贝构造,都在return返回值的时候发生。
ooolinux 2018-05-31
  • 打赏
  • 举报
回复
b=a; 相当于 b.operator=(a); operator=是一个成员函数。 c=b=a; 相当于 c.operator=(b.operator=(a));
ooolinux 2018-05-31
  • 打赏
  • 举报
回复
人家都忙着,你这种问题应该发在C++板块的。
vloso 2018-05-31
  • 打赏
  • 举报
回复
引用 4 楼 u010165006 的回复:
b=a; 相当于 b.operator=(a); operator=是一个成员函数。 c=b=a; 相当于 c.operator=(b.operator=(a));
感觉论坛好像没什么人啊,只有哥们冒头
vloso 2018-05-30
  • 打赏
  • 举报
回复


请问这行代码里的参数传递是调用了那个传进去的
ooolinux 2018-05-30
  • 打赏
  • 举报
回复
运行结果:
ooolinux 2018-05-30
  • 打赏
  • 举报
回复
简单的: Student.h
#include <string>
using namespace std;

class Student
{
private:
	string name;
	int age;
public:
	Student();
	Student(string name, int age);
	~Student();
	Student& operator=(const Student& rhs);
	void display() const;
};
Student.cpp
#include "Student.h"
#include <iostream>
using namespace std;

Student::Student()
{
}

Student::Student(string name, int age)
{
	this->name = name;
	this->age = age;
}

Student::~Student()
{
}

void Student::display() const
{
	cout << name << "\t" << age << endl;;
}

Student& Student::operator=(const Student& rhs)
{
	name = rhs.name + "的克隆";
	age = rhs.age;
	return *this;
}
main.cpp
#include "Student.h"

int _tmain(int argc, _TCHAR* argv[])
{
	Student a("xiaomin", 20);
	Student b, c;
	c = b = a;
	a.display();
	b.display();
	c.display();
	return 0;
}

13,825

社区成员

发帖
与我相关
我的任务
社区描述
C++ Builder相关内容讨论区
社区管理员
  • 基础类社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧