zoukankan      html  css  js  c++  java
  • c++,给常成员变量赋值

    C++中,常成员变量只能在构造函数赋值,且只能通过参数列表的形式赋值,且必须在构造函数赋值。

    (拥有常成员变量的类的构造函数必须对所有成员变量赋值。)

    #include <iostream>
    using namespace std;
    
    class Demo
    {
    public:
        int const a;
        const int b;
        Demo(int x,int y,char *hello);
        Demo(int x,int y );
        void show(void);
    };
    
    Demo::Demo(int x,int y,char* hello):a(x),b(y)
    {
        cout<<hello<<endl;
    }
    Demo::Demo(int x,int y):a(x),b(y)
    {
         
    }
    
    void Demo::show(void)
    {
        cout << "a="<<this->a<<endl;
        cout << "b="<<this->b<<endl;
    }
    
     
    int main() {
        //Demo one(1 , 123);
        Demo one(1 , 123,"good job");
        one.show();
    
        while(1);
        return 0 ;
    } 

    //测试:赋值成功
    a=1
    b=123
  • 相关阅读:
    观察者模式
    工厂模式
    单例模式
    代理模式
    策略模式
    Ioc容器
    Spring概述
    02:入门
    01:背景
    编译原理感悟
  • 原文地址:https://www.cnblogs.com/mylinux/p/4091660.html
Copyright © 2011-2022 走看看