使用c ++抽象类

时间:2018-03-22 00:01:42

标签: c++ arduino embedded abstract-class

我正在编写一个程序来处理一块硬件(一个小OLED屏幕)。它的基本结构将是:

  1. 用户界面类(类似“drawCircle”,...)
  2. 的功能
  3. 为OLED提供基本命令的类(“setPixel”,...)
  4. 用于管理通信接口的类(“sendCommand”,...)
  5. 其中1.包含2.其中包含3.,并且只有1.可由用户访问。 改变2.将允许使用不同的OLED控制器芯片,并且改变3.以使用不同的通信接口(例如SPI或I2C)。让我们谈谈能够改变通信界面。

    每个界面都需要只有用户知道的不同设置:例如I2C地址可能因物理配置而异,SPI接口可能要求用户选择从选择引脚。所以在第1层必须有一些特定于接口的设置,但它应该是“最小的”;我的想法是为每个界面提供不同的构造函数。因为我希望每个“层”(1.,2。和3.)尽可能少地了解较低的那些我想使用抽象类:第1层应该只知道一个通​​用的“设备” class和layer 2.只关于“接口”。

    这是我对c ++继承的第一个实用方法之一,并试图通过阅读或多或少完整和写得很好的文章和教程解决我当前的问题,我迷失了太多的信息,我无法集中注意力关于这个问题。

    这是我的问题,因此我的问题。

    考虑以下代码。为简单起见,我将所有硬件内容替换为数字示例:Number代表我的Interface类,DigitText代表SPI和{ {1}}。

    I2C

    如果用户(即以下#include <iostream> #include <string> // an abstract class class Number { public: // only pure virtual functions virtual void addOne() = 0; }; // a class derived from Number class Digit : public Number { public: Digit(int x) : n(x) {} void addOne() { std::cout << n << " + 1 = " << n + 1 << "\n"; } private: const int n; }; // another class derived from Number class Text : public Number { public: Text(std::string x) : n(x) {} void addOne() { std::string x; if (n == "one") x = " two"; else if(n == "two") x = " three"; else if(n == "three") x = " four"; else x = "... sorry, I don't know"; std::cout << n << " plus one equals" << x << "\n"; } private: std::string n; }; 函数的作者)知道上述所有代码,他可能会这样做:

    main

    但如果他不知道怎么办?我没有尝试过多种可能性,包括如下:

    // a class containing a Number
    class C {
    public:
        C(Digit x) : num(x) {};
        C(Text x)  : num(x) {};
    
        void compute() {
            num.addOne();
        }
    
    private:
         Number& num;
    };
    
    
    int main () {
    
        C a(Digit(2));
        C b(Text("two"));
    
        a.compute();
        b.compute();
    
        return 0;
    }
    

    这给了我以下错误。

    // a class containing a Number
    class C {
    public:
        C(int x)          : num(Digit(x)) {};
        C(std::string x)  : num(Text(x))  {};
    
        void compute() {
            num.addOne();
        }
    
    private:
        Number& num;
    };
    
    
    int main () {
    
        C a(2);
        C b("two");
    
        a.compute();
        b.compute();
    
        return 0;
    }
    


    感谢您的阅读和任何帮助

0 个答案:

没有答案
相关问题