|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- #include <iostream>
- using namespace std;
- #include <string>
- template<class T>
- class Maker
- {
- public:
- Maker(T val)
- {
- this->val =val;
- }
- T getval()
- {
- return this->val;
- }
- private:
- T val;
- };
- void printfInt(const Maker<int> &m)
- {
- cout<<"val: "<<m.getval();
- }
- int main()
- {
- Maker<int> m(20);
- printfInt(m);
- return 0;
- }
复制代码
报错:[Error] passing 'const Maker<int>' as 'this' argument of 'T Maker<T>::getval() [with T = int]' discards qualifiers [-fpermissive]
问题:为什么会报错? 如何解决?
这里不加const 就没事 但是,加上就会报错
- #include <iostream>
- using namespace std;
- #include <string>
- template<class T>
- class Maker
- {
- public:
- Maker(T val)
- {
- this->val = val;
- }
- T getval() const // <------------------- 注意这里
- {
- return this->val;
- }
- private:
- T val;
- };
- void printfInt(const Maker<int>& m)
- {
- cout << "val: " << m.getval();
- }
- int main()
- {
- Maker<int> m(20);
- printfInt(m);
- return 0;
- }
复制代码
|
|