gpt4 book ai didi

c++ - 模板函数中从 ‘const int*’ 到 ‘int*’ 的无效转换

转载 作者:行者123 更新时间:2023-11-30 04:42:04 26 4
gpt4 key购买 nike

class A{
private:
T x;
public:
A():x(0){}
A(T x1):x(x1){}

void printInfo(const T& a){
cout<<"Succes1"<<endl;
}
};

class B{
private:
int x;
A<int*> var;
public:
B():x(0){}
B(int x1):x(x1){}

void printInfo(const int * a){
var.printInfo(a);
}
};

问题在于

void printInfo(const int * a){
var.printInfo(a);
}

它给出一个错误,说从‘const int*’到‘int*’的无效转换

但适用于 int *aint *const a

不应该在类 A 中使 printInfo 无效

void printInfo(const int* a)

这是正确的吗?

cont int *p, //pointer to constant int

int* const p //constant pointer to int

如果是这样的话,应该有错误

printInfo(int* const a)

不与

printInfo(const int * a)

最佳答案

Shouldn't void printInfo in class A look like

void printInfo(const int* a)

Is this correct?

不,问题是你声明了var作为A<int*>B , 所以 A

void printInfo(const T& a); 

真的是

void printInfo( int* const& a); 

不是

void printInfo( int const* & a); 

因此,对于 B 中的调用工作你需要申报 var作为A<int const*> .见编译版本here .

关于c++ - 模板函数中从 ‘const int*’ 到 ‘int*’ 的无效转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58921841/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com