例如,我有代码:
class test{
public:
test(){
cout<<endl<<"TEST";
}
void another(){
cout<<endl<<"Another";
}
};
int main(){
test chk = chk;
chk.another();
}
Run Code Online (Sandbox Code Playgroud)
在这里,我已经完成了新创建的类型对象的初始化test.
难道这样的初始化服务特殊用途,不这样初始化做任何事情,否则不是初始化test chk;代替test chk = chk;?
我知道如果对象初始化为自身,则无法调用构造函数,但为什么呢?
我想了解更多关于对象自身的初始化.
我知道没有括号就不能调用函数,但是,假设我有这段源代码:
#include<iostream>
using namespace std;
ostream& test(ostream& os){
os.setf(ios_base::floatfield);
return os;
}
int main(){
cout<<endl<<scientific<<111.123456789;
cout<<endl<<test<<111.123456789;
}
/// Output:
/// 1.11235e+002
/// 111.123
Run Code Online (Sandbox Code Playgroud)
没有左移位运算符重载任何,但是当我打电话的test(ostream& os)功能中cout的main功能,它不需要任何括号.我的问题是为什么?
我的问题是关于在函数中通过引用返回.例如,我有代码:
main.cpp中
class Vector{
public:
Vector(int a , int b){
x = a;
y= b;
}
Vector() { }
int x = 1;
int y = 1;
};
Vector& operator+(const Vector& lvec ,const Vector& rvec ){
Vector resvec;
resvec.x = lvec.x + rvec.x;
resvec.y = lvec.y + rvec.y;
return resvec;
}
int main(){
Vector vecone(1,2);
Vector vectwo(1,2);
Vector resultvec = vecone + vectwo;
cout<<endl<<"X:"<<resultvec.x<<endl<<"Y:"<<resultvec.y;
}
Run Code Online (Sandbox Code Playgroud)
它运行并运行良好,但是,我似乎不理解运算符重载函数中引用运算符(&)的用途,但我在很多源代码中都看到它包含运算符重载函数.当我解雇运算符时程序似乎运行得很好,所以我的问题是 - 在函数中通过引用返回的目的是什么?它在我提供的代码中是否有特殊目的?
以下示例来自Bjarne的书 - "使用C++编程和原理",示例:
fstream fs;
fs.open("foo",ios_base::in);
fs.close();
fs.open("foo",ios_base::out);
Run Code Online (Sandbox Code Playgroud)
我理解我在使用枚举时使用范围解析运算符,当在类中有类时,但我不明白的是,使用ios_base::in和时范围解析运算符的目的是什么ios_base::out?
假设我有这个程序:
const int width = 4;
void test(int&){}
int main() {
test(width);
}
Run Code Online (Sandbox Code Playgroud)
这将无法编译.我注意到名称(例如宽度)的常量值(也是枚举常量)不能通过引用传递.为什么会这样?
例如:
struct test
{};
void thing(test())
{}
int main()
{
thing(test());
}
Run Code Online (Sandbox Code Playgroud)
这段代码会给我错误; 但是,下一个例子不会给我错误:
void thing(int())
{}
int main()
{
thing(int());
}
Run Code Online (Sandbox Code Playgroud)
我的主要问题是,为什么第一个例子不可能而第二个例子是?最终,双方test并int有类型,所以我想不出为什么声明的一个匿名对象test在thing函数参数列表是不可能的,而声明类型的匿名对象int在thing函数参数列表.
我看到可以使用vector创建一个指针数组,但是,我不希望这样.下面的示例是一种创建指向int数组的指针的方法吗?
#include <iostream>
using namespace std;
int main() {
int* arr[4];
for (int i=0; i<4; ++i) {
cout<<endl<<arr[i];
}
}
Run Code Online (Sandbox Code Playgroud)
这将生成一个指向int数组的指针,并显示数组中每个索引的内存地址.现在我几乎没有问题.它是一种在没有向量的情况下创建指向int数组的指针的正确方法吗?另外,如果我想在给定示例中初始化每个内存地址中的值,它是如何完成的?最后为什么&arr等于arr?