C++中 int i 与 int &i 注意事项

1.int i 传值,int & i 传引用

int i不会回带参数,而int &i可以回带参数,如

#include <iostream>

void test1(int i)
{
	i = 7;
}

void test2(int &i) //要限制参数改动,可以加const限制
{
	i = 7;
}

int main()
{
	int t1 = 10;
	test1(t1);
	std::cout << t1 << std::endl; //输出为10

	int t2 = 10;
	test2(t2);
	std::cout << t2 << std::endl;	//输出为7

	return 0;
}

2. int i 可赋予常量,而int & i 不能

#include <iostream>

void test1(int i)
{
	i = 7;
}

void test2(int &i)
{
	i = 7;
}

int main()
{
	int i = 10;		//合法
	int &i1 = 10;	//编译错误

	test1(10);		//合法
	test2(10);		//编译错误

	return 0;
}

3. int &i 相当于别名,而int i 只是拷贝

#include <iostream>

int main()
{
	int t1 = 10;
	int t2 = 10;
	int i1 = t1;	//复制
	int &i2 = t2;	//别名
	
	i1 = 7;
	i2 = 7;

	std::cout << t1 << std::endl;	//输出10
	std::cout << t2 << std::endl;	//输出7

	return 0;
}

最后,我们再来看一下个例子

#include <iostream>
class A{
public:
	A(int a, int b):i1(a),i2(b){};

public:
	int i1;
	int &i2;
};

int main()
{
	A a(45,60);
	std::cout << a.i1 << " " << a.i2 << std::endl;
	return 0;
}

在电脑上运行之后,你会发现,第一个数字正常,而第二个数字明显是一个未定义的值,例如我运行后得到的结果是

45  1400458944

这是因为我们在构造一个对象的时候,调用了构造函数,而A的构造函数的参数传递为传值方式,所以,当调用时,相当于有一个

int b = 60 
存在,而 i2(b) 相当于将
int &i2 = b;
而当构造函数调用完成,b的作用域结束,b被销毁,而i2指向一个已经被销毁的地方,所以会出现未定义的运行结果。
我们再贴一段程序,和上面的一段相对应,只是,这次,我们将会获得 45 60  的结果
#include <iostream>
class A{
public:
	A(int a, int &b):i1(a),i2(b){};

public:
	int i1;
	int &i2;
};

int main()
{
	int t  = 60;
	A a(45,t);
	std::cout << a.i1 << " " << a.i2 << std::endl;
	return 0;
}
  • 21
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++ ,string 类型是一个非常常用的字符串类,可以方便地进行字符串的操作。使用 string 类型需要注意以下几点: 1. 头文件:需要包含 <string> 头文件。 2. 声明:需要使用 std 命名空间,或者在全局范围内使用 using namespace std; 声明。 3. 初始化:可以直接使用字符串字面量或者其他 string 对象初始化。 4. 操作:可以使用常规的字符串操作,如比较、拼接、查找、替换等。 5. 长度:可以使用 size() 或者 length() 方法获取字符串的长度。 6. 遍历:可以使用 for 循环或者迭代器遍历字符串的每一个字符。 7. 转换:可以使用 c_str() 方法将 string 类型转换为 const char* 类型,或者使用 stoi()、stof() 等方法将 string 类型转换为其他类型。 示例代码: ``` #include <iostream> #include <string> using namespace std; int main() { string s1 = "hello"; string s2("world"); string s3 = s1 + " " + s2; cout << s3 << endl; if (s1 == "hello") { cout << "s1 equals to hello" << endl; } int index = s3.find("world"); if (index != string::npos) { cout << "world found at index " << index << endl; } for (char c : s3) { cout << c << " "; } cout << endl; const char* cstr = s3.c_str(); cout << "cstr: " << cstr << endl; return 0; } ``` 输出结果: ``` hello world s1 equals to hello world found at index 6 h e l l o w o r l d cstr: hello world ``` 需要注意的是,string 类型的底层实现是动态分配的内存,因此在进行大量字符串操作时需要注意内存的使用。同时,由于 string 对象的复制和传递涉及到内存的拷贝,因此也需要注意效率问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值