cpp空数组声明 [英] cpp empty array declaration

查看:159
本文介绍了cpp空数组声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我有以下测试代码,我对cpp感到困惑。

Hello I have the following test code and I am confused about cpp.


  1. 如果您在library.h中声明数组有一个空的元素子句。编译器会选择什么?

  1. If you declare in library.h an array with an empty element clause .. what will the compiler pick? It does also not complain, I use Cygwin.

在library.cpp中,我为两个元素赋值,是编译器假设一个数组有一个元素,I写入数组范围之外的第二个元素?

In library.cpp I assign values to two elements, is the compiler assuming an array with one element and I write the second element outside the scope of the array?



library.h



library.h

#ifndef LIBRARY_H
#define LIBRARY_H

class library {

public:
    void print();
    char a[];
};

#endif



library.cpp



library.cpp

#include <stdio.h>
#include "library.h"

void library::print() {
    a[0] = 'a';
    printf("1. element: %d\n", a[0]);
    a[1] = 'b';
    printf("2. element: %d\n", a[1]);
}



client.cpp



client.cpp

#include <stdio.h>
#include "library.h"

void execute();
library l;

int main() {
    l = library();
    l.print();
    return 0;
}



Makefile



Makefile

OPTIONS=-Wall

all: main

run: main
        ./main.exe

main: client.o library.o
        g++ $(OPTIONS) -o main $^

library.o: library.cpp library.h
        g++ $(OPTIONS) -c $<

.cpp.o:
        g++ $(OPTIONS) -c $<

clean:
        rm -r *.o


推荐答案


  1. 没有C / C ++语言,因此您的Q不能同时标记两者。

  2. ,您的程序只能是C ++而不是C.







public:
     void print();
     char a[];

这段代码在C ++中是非法的。 C ++中的数组大小需要为正编译时常数。解决方案是替换它:

This code is simply illegal in C++. Array size in C++ needs to be positive compile time constant. Solution is to replace it by:

public:
      void print();
      std::string a;






请注意,声明


Note that the declaration,

char a[];

在c99中有效,称为不完整的阵列类型 C标准保证 a 可以存储 char 类型的至少一个元素。这在C ++中无效。 C ++标准不允许这些。只是因为两者都是不同的语言。

is valid in c99 and it is known as Incomplete array type, the C standard guarantees that a can store atleast one element of the type char. This is not valid in C++. C++ standard does not allow these. Simply because both are different languages.

这篇关于cpp空数组声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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