[英]Why I can use the class name as a function name?
據我了解C++
,我們不能使用相同的identifier
的另一聲明:
int x;
char x; // compile-time error: redefinition.
但是這是我弄亂classes
一個例子:
#include "stdafx.h"
#include <iostream>
#include <vector>
class A {
public:
A(int);
void print()const;
friend std::ostream& operator << (std::ostream& out, A& rhs);
private:
int value1;
};
std::ostream& operator << (std::ostream& out, A& rhs) {
out << "rhs.value1 = " << rhs.value1 << std::endl;
return out;
}
A::A(int x) : value1(x) { std::cout << "ctor A(x)" << std::endl; }
void A::print()const {
std::cout << "value1: " << value1 << std::endl;
}
int A(int x) {
std::cout << "inside A(int x)" << std::endl;
return x;
}
int main(){
class A a { 0 };
a = A(7);
a.print();
std::cout << A(7) << std::endl;
std::cout << A(5) << std::endl; // here if I comment out the function a it is ok as long as I overloaded the insertion operator
// and if I add the function A it hides the insertion operator!
std::cout << std::endl;
std::cin.get();
return 0;
}
因此,如您在上面看到的,每當我聲明class A
的對象時,我都必須添加關鍵字class
,否則會出現編譯時錯誤。 為什么?
a = A(7);
函數調用和返回值傳遞給的構造函數class A
,它接受一個整數。 還是根本沒有函數調用而只有ctor
調用? 從我的角度來看,您有一個類A和一個函數A,因此必須指出A是一個類或函數,這就是為什么在聲明A的對象時必須添加“類”的原因。
根據以下代碼,定義了兩個類A和B,它們完全相同,但是A可以是函數或類,因此,在聲明對象A時,必須在A之前添加“類”,而聲明B的對象則無需添加“類”
對於第二個問題,將調用第一個函數A,並將其返回值用於構造對象a。 您可以看到第一個x = 7在函數A中,而ctor x = 8是因為該函數返回x + 1。
輸出:
ctor A(x) x=0
inside A(int x) x=7
ctor A(x) x=8
ctor B(x)
測試代碼:
#include <iostream>
#include <vector>
class A {
public:
A(int);
private:
int value1;
};
class B {
public:
B(int);
private:
int value1;
};
B::B(int x) : value1(x) { std::cout << "ctor B(x)" << std::endl; }
A::A(int x) : value1(x) { std::cout << "ctor A(x) x=" << x <<std::endl; }
int A(int x) {
std::cout << "inside A(int x) x=" << x << std::endl;
x=x+1;
return x;
}
int main(){
class A a(0);
a = A(7);
B b(0);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.