在C ++中分配值后声明类变量 [英] Declaring class variables after assigning them values in C++

查看:172
本文介绍了在C ++中分配值后声明类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里我有一个类 Shape

class Shape 
{
   public:
      void setWidth(int w)
      {
         width = w;
      }
      void setHeight(int h)
      {
         height = h;
      }
   protected:
      int width;
      int height;
};

它编译很好,但是我怎么可以分配 width height 值,即使我以前没有声明它们吗?

It compiles just fine, but how is it that I am even allowed to assign width and height values even though I didn't declare them previously? How does the compiler know at this point what they are?

推荐答案

基本上语言的工作方式和具有成员函数定义inline的类由编译器重写为

Basically the language works as if a class with member function definitions inline, is rewritten by the compiler as

class Shape 
{
   public:
      void setWidth(int w);
      void setHeight(int h);

   protected:
      int width;
      int height;
};

inline void Shape::setWidth(int w)
{
   width = w;
}

inline void Shape::setHeight(int h)
{
   height = h;
}

这有很大的解释力,但是,

This has great explanatory power in general, but, heads up: it may not necessarily be so good a model for nested classes.

一般注释:


  • 努力提供实用的介面。例如。如果设置形状的宽度或高度更新其屏幕演示,则如果我要更改两者,则使用将导致两个屏幕更新的当前接口。

  • Strive to provide practical interfaces. E.g. if setting the width or height of a shape updates its screen presentation, then if I want to change both, with the current interface that will cause two screen updates.

而不是属性设置器,考虑检查的函数,例如在这种情况下, resize 函数或一组函数。

Instead of attribute setters, consider functions that either do or inspect, e.g. in this case, a resize function or set of functions.

protected 数据通常不是一个好主意。除非你有很好的理由,否则默认为 public private

protected data is generally not a good idea. Make it public or private by default, unless you have a very good reason.

这篇关于在C ++中分配值后声明类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆