1
爲什麼我收到提示構造函數創建const對象
../implicit-explicit.cpp:44:10: error: invalid initialization of non-const reference of type ‘BWSize&’ from an rvalue of type ‘char’
../implicit-explicit.cpp:36:6: error: in passing argument 1 of ‘void func(BWSize&)’
,當我從函數void func(const BWSize & s)
刪除const
根據我的理解構造函數返回的不是常量的值。
代碼
// implicit-explicit.cpp by Bill Weinman <http://bw.org/>
#include <iostream>
const std::size_t maxlen = 1024; // maximum length of bwString
class BWSize {
std::size_t _size;
public:
BWSize(std::size_t); // constructor: size from int
BWSize(const char *); // constructor: size from c-string
std::size_t size() const;
};
BWSize::BWSize(const std::size_t n) {
std::cout << "BWSize from int" << std::endl;
_size = (n <= maxlen) ? n : 0;
}
BWSize::BWSize(const char * s) {
std::cout << "constructor: BWSize from c-string" << std::endl;
for(std::size_t i = 0; i < maxlen; i++) {
if(s[i] == '\0') {
_size = i;
return;
}
}
_size = 0;
}
std::size_t BWSize::size() const {
return _size;
}
using namespace std;
void func(const BWSize & s) {
cout << "s.size() is " << s.size() << endl;
}
int main(int argc, char ** argv) {
BWSize s = 'x';
cout << "s.size() is " << s.size() << endl;
func('x');
return 0;
}
小記:你可以聲明你的構造函數爲'explicit'以避免隱式轉換(如果不需要) – lolando
當然,你不是指'func(「x」)'? – Roddy